package common

import (
	"fmt"
	"github.com/gin-gonic/gin"
	websocket2 "github.com/gorilla/websocket"
	"net/http"
	"server/base"
	"server/common/utils"
	websocket3 "server/pkg/websocket"
	"time"
)

var Websocket = new(websocket)

type websocket struct{}

// 升级websocket
var upGrader = websocket2.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func (*websocket) Connect(c *gin.Context) {
	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		fmt.Print("websocket-connect:err", err.Error())
		c.String(http.StatusOK, "websocket upgrade err", err.Error())
		return
	}

	// 构建用户信息
	roleId := utils.GetSocketUserId(c)
	conn := websocket3.NewUserConn(roleId, utils.CreateConnId(roleId), ws)

	// 记录上线状态
	base.App.WebSocketHub.Join(conn)
	defer base.App.WebSocketHub.Leave(conn)

	for true {
		err = ws.SetReadDeadline(time.Now().Add(20 * time.Second))

		if err != nil {
			fmt.Print("websocket-connect:err", err.Error())
			return
		}
		_, m, err := ws.ReadMessage()
		fmt.Print(m)
		if err != nil {
			fmt.Print("websocket-connect:err", err.Error())
			break
		}
	}

	ws.Close()
}
